<template>
  <div>
    <div v-if="!file">
      <div class="container">
        <div class="text">
          <i class="el-icon-upload"></i>
          <p>点击上传或直接将视频文件拖拽到此区域</p>
        </div>
        <input
          type="file"
          @change="handleFileChange"
          accept="video/*"
        >
      </div>
    </div>
    <div v-if="file">
      <h2>
        发布作品
      </h2>
      作品描述
      <el-input
        type="textarea"
        :rows="2"
        placeholder="请输入内容"
        v-model="text"
      >
      </el-input>
      作品预览
      <video
        v-show="videoUrl"
        ref="videoPlayer"
        class="video-js vjs-default-skin haha"
        controls
        autoplay
        muted
      >
      </video>
      设置封面
      <button @click="startUpload">开始上传</button>
      <el-progress :percentage="uploadProgress"></el-progress>
      <div>{{ message }}</div>
    </div>
  </div>
</template>

<script>
import videojs from "video.js";
import "@/assets/video-js.css";

export default {
  name: "videoUpload",
  data() {
    return {
      file: null,
      videoFile: null,
      videoUrl: "",
      text: "",
      uploadProgress: 0,
      chunkSize: 1024 * 1024, // 1MB 分片大小
      totalChunks: 0,
      uploadedChunks: 0,
      message: "",
    };
  },
  mounted() {},
  methods: {
    // 选择本地文件上传
    handleFileChange(event) {
      this.videoFile = event.target.files[0];
      this.file = event.target.files[0];
      const selectedFile = event.target.files[0];
      if (selectedFile) {
        this.videoUrl = URL.createObjectURL(selectedFile);

        // 使用 $nextTick 来确保组件渲染完毕
        this.$nextTick(() => {
          const videoPlayer = this.$refs.videoPlayer;

          if (videoPlayer) {
            // 计算视频的宽度和高度
            const video = document.createElement("video");
            video.addEventListener("loadedmetadata", () => {
              const videoWidth = video.videoWidth;

              // 根据视频大小设置播放器的大小
              videoPlayer.style.width = videoWidth + "px";
            });
            videoPlayer.src = this.videoUrl;
            video.src = this.videoUrl;
          }
        });
      }
    },
    //#region
    // 开始上传视频
    /* async startUpload(uploadedChunks) {
      if (!this.file) {
        this.$message({
          type: "error",
          message: "请选择一个视频文件",
        });
        return;
      }

      this.totalChunks = Math.ceil(this.file.size / this.chunkSize);

      const formData = new FormData();
      formData.append("text", this.text);
      formData.append("file", this.file);
      formData.append("totalChunks", this.totalChunks);

      const startChunkNumber = uploadedChunks;
      await this.uploadChunks(formData, startChunkNumber);
    }, */
    // 分片上传
    /* async uploadChunks(formData, startChunkNumber) {
      let chunkNumber = startChunkNumber;
      // this.uploadedChunks = startChunkNumber;

      const uploadChunk = async (chunkNumber) => {
        const start = chunkNumber * this.chunkSize;
        const end = Math.min(start + this.chunkSize, this.file.size);
        const chunk = this.file.slice(start, end);

        formData.set("chunkNumber", chunkNumber);
        formData.set("chunk", chunk);

        try {
          const response = await this.uploadChunk(formData);

          if (response.status === 200) {
            this.uploadedChunks++;
            this.uploadProgress =
              (this.uploadedChunks / this.totalChunks) * 100;
            this.message = `已上传 ${this.uploadedChunks} / ${this.totalChunks} 分片`;

            if (chunkNumber < this.totalChunks - 1) {
              // 继续上传下一个分片
              uploadChunk(chunkNumber + 1);
            } else {
              this.message = "上传完成";
            }
          } else {
            this.message = "文件上传失败";
          }
        } catch (error) {
          console.error("上传错误:", error);
          this.message = "文件上传失败";
        }
      };

      uploadChunk(chunkNumber);
    }, */
    // 上传
    /* async uploadChunk(formData) {
      // TODO:使用 Axios 或其他 HTTP 客户端库将分片数据上传到后端
    }, */
    //#endregion

    // 上传视频
    async uploadVideo() {
      const formData = new FormData();
      // TODO:字段可能需要更改
      formData.append("video", this.videofile);

      try {
        let result = await this.$API.reqUploadVideo(formData);
        if (result.code == 200) {
          // 视频上传成功，上传文字
          const formData2 = new formData();
          // TODO:字段可能需要更改
          formData2.append("text", this.text);
          let result2 = await this.$API.reqUploadText(formData2);
          if (result2.code == 200) {
            this.$message({
              type: "success",
              message: "作品发布成功！",
            });
          }
        }
      } catch (error) {
        this.$message({
          type: "error",
          message: "视频上传失败",
        });
      }
    },
  },
  beforeDestroy() {
    if (this.player) {
      this.player.dispose();
    }
  },
};
</script>

<style scoped>
.haha {
  max-width: 300px;
  height: auto;
}

.container {
  position: relative;
  width: 500px;
  height: 300px;
  background-color: #f4f5f5;
  border: 1px dashed #e3e4e5;
  margin: 100px auto;
}

.container input {
  width: 100%;
  height: 100%;
  opacity: 0;
  z-index: 100;
}

.container .text {
  position: absolute;
  top: 0;
  left: 0;
  width: 500px;
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.text i {
  font-size: 70px;
}

.text p {
  margin: 0;
  padding: 0;
}
</style>